import config from "@/pages.json";

const pages = config.pages;
const reLaunchList = ["login", "index", "me", "organization"];

export function to(page_name, params) {
  if (!page_name || typeof page_name !== "string" || page_name.toLowerCase() !== page_name) {
    // 参数不合法
    console.error(page_name, "Invalid page_name provided");
    uni.showToast({
      title: "Invalid page_name provided",
      duration: 2000,
      icon: "error",
    });
    return;
  }

  const url = `pages/${page_name}/${page_name}`;
  const pageExists = pages.find((item) => item.path === url); /* 检查页面是否存在的逻辑 */

  if (!pageExists) {
    console.error("Page does not exist");
    uni.showToast({
      title: "Page does not exist",
      duration: 2000,
      icon: "error",
    });
    return;
  }

  const type = reLaunchList.includes(page_name) ? "reLaunch" : "navigateTo";

  // 跳转
  uni.$uv.route(
    {
      type,
      url: `/${url}`,
      // 拦截器
      intercept(params, next) {
        // console.log(params, next);
        uni.showLoading({
          title: "等待中...",
        });
        // 模拟处理等待
        // setTimeout(() => {
        uni.hideLoading();
        next(true);
        // }, 1000);
      },
      // 监听器，获取被打开页面传送到当前页面的数据
      events: {
        acceptDataFromOpenedPage(data) {
          console.log("route = ", data);
        },
        someEvent(data) {
          console.log("route = ", data);
        },
      },
    },
    params
  );
}

export default function registerRouter(app) {
  app.config.globalProperties.$to = to;
}
